package com.elitel.common.filter;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.elitel.common.mongodb.GeneralCallInterfaceRecord;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
//import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

//@Component
//@Order(1)
@Slf4j
public class GeneralBusinessWebControllerFilter implements Filter{

    //@Autowired
   // private MongoTemplate mongoTemplate;

    // @PostConstruct
    // private void init(){
    //     if(mongoTemplate.collectionExists(GeneralCallInterfaceRecord.class))
    //         return;

    //     mongoTemplate.createCollection(GeneralCallInterfaceRecord.class);
    // }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        GeneralCallInterfaceRecord record = GeneralCallInterfaceRecord.startRecordIfNecessary(httpRequest);

        try{
            chain.doFilter(request, response);

            if(record == null) return;
            record.setResponseRelativeInfo((HttpServletResponse)response);

        }catch(Exception e){
            if(record != null) record.setExceptionMessage(e);
            log.error(e.getMessage());
            e.printStackTrace();
//            log.error(e.getStackTrace().toString());
            throw e;

        }finally{
            if(record == null) return;
            // here is record server Record into time series database
            recordLogIntoMongoDB(record);
        }
    }

    private void recordLogIntoMongoDB(GeneralCallInterfaceRecord record){
        if(record == null) return;
        if(true)
            return;
        try{
           // mongoTemplate.save(record);

        }catch(Exception e){
            log.error(e.getMessage());
        }
    }

    public boolean checkPathBelongBussinessService(String requestUrl){
        return true;

    }
}
